﻿using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.SdkTypeProxy.Metadata;

namespace Custom.Crm.Sdk
{
    public class CustomTargetImage
    {
        public string GetValue(IPluginExecutionContext context, string attributeName)
        {
            try
            {
                switch (context.MessageName.ToLower())
                {
                    case "create":
                    case "update":
                        return CustomDynamicEntity.GetAttributeValue(((DynamicEntity)context.PostEntityImages["Target"]).Properties[attributeName], false);
                    case "delete":
                        if (context.PreEntityImages["AsynchronousStepPrimaryName"] != null)
                            return CustomDynamicEntity.GetAttributeValue(((DynamicEntity)context.PreEntityImages["AsynchronousStepPrimaryName"]).Properties[attributeName], false);
                        else
                            return CustomDynamicEntity.GetAttributeValue(((DynamicEntity)context.PreEntityImages["Target"]).Properties[attributeName], false);
                    default:
                        if (context.PostEntityImages["Target"] != null)
                            return CustomDynamicEntity.GetAttributeValue(((DynamicEntity)context.PostEntityImages["Target"]).Properties[attributeName], false);
                        if (context.PreEntityImages["Target"] != null)
                            return CustomDynamicEntity.GetAttributeValue(((DynamicEntity)context.PreEntityImages["Target"]).Properties[attributeName], false);
                        break;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return null;
            }

            return null;
        }

        public Guid GetEntityId(IPluginExecutionContext context)
        {
            IMetadataService metaData = context.CreateMetadataService(true);

            return this.GetEntityId(context, metaData);
        }

        public Guid GetEntityId(IPluginExecutionContext context, IMetadataService metaData)
        {
            // Get the metadata about the current entity.
            RetrieveEntityRequest req = new RetrieveEntityRequest();
            req.LogicalName = context.PrimaryEntityName;
            RetrieveEntityResponse res = (RetrieveEntityResponse)metaData.Execute(req);

            return this.GetKeyValue(context, res.EntityMetadata.PrimaryKey);
        }

        public Guid GetKeyValue(IPluginExecutionContext context, string keyName)
        {
            string val = this.GetValue(context, keyName);

            if (val != null)
                return new Guid(val);
            else
                return Guid.Empty;
        }
    }
}
